package com.pai4j.message.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * 订阅配置模型
 * 用户的消息订阅配置
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SubscriptionConfig implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 订阅ID
     */
    private String subscriptionId;

    /**
     * 用户ID
     */
    private String userId;

    /**
     * 订阅类型
     * 可选值：message_type, resource, user
     */
    private String subscriptionType;

    /**
     * 订阅的消息类型列表
     */
    @Builder.Default
    private Set<String> messageTypes = new HashSet<>();

    /**
     * 订阅的资源ID列表
     */
    @Builder.Default
    private Set<String> resourceIds = new HashSet<>();

    /**
     * 订阅的用户ID列表
     */
    @Builder.Default
    private Set<String> subscribedUserIds = new HashSet<>();

    /**
     * 订阅的渠道列表
     */
    @Builder.Default
    private Set<String> channels = new HashSet<>();

    /**
     * 推送频率
     * 可选值：realtime, hourly, daily
     */
    @Builder.Default
    private String frequency = "realtime";

    /**
     * 是否启用
     */
    @Builder.Default
    private Boolean enabled = true;

    /**
     * 静默时段开始时间（小时）
     */
    private Integer quietStartHour;

    /**
     * 静默时段结束时间（小时）
     */
    private Integer quietEndHour;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    private LocalDateTime updateTime;

    /**
     * 判断是否订阅了指定消息类型
     */
    public boolean isSubscribedToMessageType(String messageType) {
        return enabled && (messageTypes == null || messageTypes.isEmpty() || messageTypes.contains(messageType));
    }

    /**
     * 判断是否订阅了指定资源
     */
    public boolean isSubscribedToResource(String resourceId) {
        return enabled && (resourceIds == null || resourceIds.isEmpty() || resourceIds.contains(resourceId));
    }

    /**
     * 判断是否订阅了指定用户
     */
    public boolean isSubscribedToUser(String targetUserId) {
        return enabled && (subscribedUserIds == null || subscribedUserIds.isEmpty() || subscribedUserIds.contains(targetUserId));
    }

    /**
     * 判断当前是否在静默时段
     */
    public boolean isInQuietPeriod() {
        if (quietStartHour == null || quietEndHour == null) {
            return false;
        }

        int currentHour = LocalDateTime.now().getHour();
        
        if (quietStartHour < quietEndHour) {
            // 例如：22:00 - 08:00
            return currentHour >= quietStartHour && currentHour < quietEndHour;
        } else {
            // 跨天的情况，例如：22:00 - 08:00
            return currentHour >= quietStartHour || currentHour < quietEndHour;
        }
    }
}

